<?php


namespace App\Modules\MemberCard\Criterias;


use Flower\Core\Repository\Contracts\RepositoryInterface;
use Flower\Core\Repository\Criterias\BaseCriterias;

class GetCenterCardFlowListCriteria extends BaseCriterias
{
    private $params;
    public function __construct($storeId,$startDate,$endDate,$isList,$user_id=null)
    {
        $this->params = [
            'store_id' =>$storeId,
            'start_date' => $startDate,
            'end_date' =>$endDate,
            'is_list'  => $isList,
            'user_id'  => $user_id
        ];
    }

    public function apply($model, RepositoryInterface $repository)
    {
        $user_id = $this->params['user_id'];
        $result = $model
            ->select(['member_card_flow.id','card_id','member_card_flow.member_id','member_card_flow.type','member_card_flow.created_at'])
            ->with('member:id,name,face')
	        ->with(['card'=>function($v){
	        	$v->select(['id','name','attribute','type_id'])->with('cardType:id,name');
	        }])
            ->leftJoin('member_card','card_id','member_card.id')
            ->whereDate('member_card_flow.created_at', '>=',$this->params['end_date'])
            ->whereDate('member_card_flow.created_at', '<=',$this->params['start_date'])
            ->when($user_id,function ($query) use ($user_id){
                $query->where('member_card.user_id',$user_id);
            })
            ->where(['member_card_flow.store_id'=>$this->params['store_id']])
	        ->whereIn('member_card_flow.type',[1,4])
            ->orderByDesc('member_card_flow.created_at');
        return  $this->params['is_list'] ? $result->limit(5) : $result;

    }

}
